package com.chengliang.bbs.controller;

import com.chengliang.bbs.entry.*;
import com.chengliang.bbs.service.ExperienceService;
import com.chengliang.bbs.service.JieServsice;
import com.chengliang.bbs.service.JieStatusService;
import com.chengliang.bbs.service.ReplyService;
import com.chengliang.bbs.type.ColumnType;
import com.chengliang.bbs.type.RewardValue;
import com.chengliang.bbs.type.TechnologyType;
import com.chengliang.bbs.util.FileUtils;
import com.chengliang.bbs.util.StringUtil;
import com.chengliang.bbs.util.UserUtils;
import com.wf.captcha.utils.CaptchaUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestWrapper;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;

/**
 * 解答
 * @author: chengliang
 * @create: 2019-08-07 14:30
 */
@Controller
@Slf4j
@RequestMapping("/jie")
public class JieController {

    private final JieServsice jieService;

    private final JieStatusService jieStatusService;

    private final ReplyService replyService;

    private final FileUtils fileUtils;

    private final ExperienceService experienceService;

    @Autowired
    public JieController(JieServsice jieService, JieStatusService jieStatusService, ReplyService replyService, FileUtils fileUtils, ExperienceService experienceService) {
        this.jieService = jieService;
        this.jieStatusService = jieStatusService;
        this.replyService = replyService;
        this.fileUtils = fileUtils;
        this.experienceService = experienceService;
    }

    /**
     * 刷新session，防止帖子编辑时间过长导致重新登录
     * 后期可使用redis 实现 编辑内容的保存
     * @return
     */
    @PostMapping("/flush")
    @ResponseBody
    public JSONResult flush(){
        return JSONResult.success();
    }

    /**
     * 帖子图片上传
     * @param file
     * @param request
     * @return
     */
    @PostMapping("/upload")
    @ResponseBody
    public JSONResult upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        String avatarUrl = fileUtils.saveFile("images", file);
        if (StringUtil.isEmpty(avatarUrl)) {
            return JSONResult.error("图片上传失败，请重试");
        }
        return JSONResult.success().append("url",avatarUrl);
    }

    /**
     * 采纳
     * @param id
     * @return
     */
    @PostMapping("/accept")
    @ResponseBody
    public JSONResult accept(Integer id){
        //验证是否是帖子作者本人，防止部分攻击
        User jieUser = jieService.getJieUserByReplyId(id);
        log.info("帖子作者信息{}",jieUser);
        if(jieUser == null || !UserUtils.currentUser().getUser().getUserId().equals(jieUser.getUserId())){
            log.info("当前登录人{}",UserUtils.currentUser().getUser());
            return JSONResult.error("无权限进行修改");
        }
        //不能采纳自己的评论
        User replyUser = replyService.getUserByReplyId(id);
        if(replyUser == null || replyUser.getUserId().equals(jieUser.getUserId())){
            return JSONResult.error("不能采纳自己哦");
        }
        return JSONResult.is(replyService.accept(id,replyUser.getUserId()),"采纳该回复");
    }

    /**
     * 回复
     * @param jieId
     * @param content
     * @return
     */
    @PostMapping("/reply")
    @ResponseBody
    public JSONResult reply(Integer jieId,String content,@RequestParam(defaultValue = "1") Integer page){
        User user = UserUtils.currentUser().getUser();
        return JSONResult.is(replyService.addReply(jieId,UserUtils.currentUser().getUser().getUserId(),content,page),"回复")
                .append("userNickName",user.getUserNickName())
                .append("userAvatar",user.getUserAvatar());
    }

    /**
     * 修改帖子
     * @param id
     * @param verCode
     * @param jieContent
     * @param request
     * @return
     */
    @PostMapping("/update/{id}")
    @ResponseBody
    public JSONResult update(@PathVariable Integer id,String verCode,String jieContent,HttpServletRequest request){
        //验证码
        //验证验证码
        if(!CaptchaUtil.ver(verCode,request)){
            CaptchaUtil.clear(request);
            return JSONResult.error("验证码输入错误,请重新输入");
        }

        //查询作者信息
        User user = jieService.getJieUserByJieId(id);
        if(user == null || !UserUtils.currentUser().getUser().getUserId().equals(user.getUserId())){
            return JSONResult.error("无权限进行修改");
        }
        return JSONResult.is(jieService.modifyJieContent(id, jieContent),"帖子修改").append("action","/q/jie/"+id);
    }

    @GetMapping("/update/{id}")
    public String updatePage(@PathVariable Integer id, Model model){
        //帖子信息
        Jie jie = jieService.getJieDetailById(id);
        log.info("修改帖子信息:{}",jie);
        if(jie == null){
            return "other/404";
        }
        //当前用户
        UserAuths userAuths = UserUtils.currentUser();
        //不是本人账号/或未登录
        if(!userAuths.getUser().getUserId().equals(jie.getJieUser().getUserId())){
            model.addAttribute("information","无权限操作该信息");
            return "other/tips";
        }
        model.addAttribute("jie",jie);
        model.addAttribute("columnTypes", ColumnType.values());
        model.addAttribute("rewardValues",RewardValue.values());
        model.addAttribute("technologyTypes", TechnologyType.values());
        return "jie/update";
    }



    @PostMapping("/delete")
    @ResponseBody
    public JSONResult delete(Integer id){
        if(UserUtils.isNotAdmin()){
            return JSONResult.error("无权限进行该操作");
        }
        return JSONResult.is(jieStatusService.updateJieStatus(new JieStatus().setJieId(id).setJieEnable(false)),"帖子删除");
    }

    @PostMapping("/status")
    @ResponseBody
    public JSONResult top(Integer id, Boolean jieTop, Boolean jieEssence, SecurityContextHolderAwareRequestWrapper request){
        if(UserUtils.isNotAdmin()){
            return JSONResult.error("无权限进行该操作");
        }
        //修改置顶状态
        if(jieTop!=null){
            return JSONResult.is(jieStatusService.updateJieStatus(new JieStatus().setJieId(id).setJieTop(jieTop)),"帖子置顶状态");
        }
        //修改加精状态
        if(jieEssence!=null){
            return JSONResult.is(jieStatusService.updateJieStatus(new JieStatus().setJieId(id).setJieEssence(jieEssence)),"帖子加精状态");
        }
        log.info("ID{}设置状态信息:置顶{}，加精{}",id,jieTop,jieEssence);
        return JSONResult.error();
    }


    /**
     * 发帖
     * @return
     */
    @GetMapping("/add")
    public String addPage(Model model){
        model.addAttribute("columnTypes", ColumnType.values());
        model.addAttribute("technologyTypes", TechnologyType.values());
        model.addAttribute("rewardValues",RewardValue.values());
        return "jie/add";
    }

    @PostMapping("/add")
    @ResponseBody
    public JSONResult add(Jie jie, String verCode,HttpServletRequest request){
        //验证验证码
        if(!CaptchaUtil.ver(verCode,request)){
            CaptchaUtil.clear(request);
            return JSONResult.error("验证码输入错误,请重新输入");
        }
        //获取当前用户ID
        UserAuths userAuths = UserUtils.currentUser();
        //提问贴检查经验值
        if(!experienceService.checkExperienceEnough(userAuths.getUser().getUserId(), jie.getRewardValue().getCode())){
            return JSONResult.error("元气不足,请勤加修炼");
        }
        //发帖
        jie.setJieUser(new User().setUserId(userAuths.getUser().getUserId()));
        jieService.sendJie(jie);
        log.info("用户ID：{} 发表帖子：{}",userAuths.getUser().getUserId(),jie);
        return JSONResult.success("发表成功").append("action","/q/jie/"+jie.getJieId());
    }


}
